//
//  TimeKeepingViewController.m
//  AlarmClock
//
//  Created by aaaa on 2016/9/29.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "BSKTimeKeepingViewController.h"
#import "SDAutoLayout.h"
#import "BSKTimeKeepingItemTableViewCell.h"
#import <AVFoundation/AVFoundation.h>

@interface BSKTimeKeepingViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIView * contentView;
@property (nonatomic,strong) UIView * circleView;
@property (nonatomic,strong) UILabel * timeLabel;
@property (nonatomic,strong) UILabel * subTimeLabel;
@property (nonatomic,strong) UIButton * startButton;
@property (nonatomic,strong) UIButton * resetButton;
@property (nonatomic,strong) UIButton * noteButton;
@property (nonatomic,strong) UITableView * timetabel;
@property (nonatomic,strong) UILabel * startLabel;
@property (nonatomic,strong) UILabel * resetLabel;
@property (nonatomic,strong) UILabel * noteLabel;
@property (nonatomic,strong) dispatch_source_t timerSource;
@property (nonatomic,assign) NSInteger minutes;
@property (nonatomic,assign) NSInteger second;
@property (nonatomic,assign) NSInteger mSecond;
@property (nonatomic,assign) NSInteger subMinutes;
@property (nonatomic,assign) NSInteger subSecond;
@property (nonatomic,assign) NSInteger subMSecond;
@property (nonatomic,strong) NSMutableArray * timeDataSourceArray;
@property (nonatomic,strong) UIView * pointView;
@property (nonatomic,strong) UILabel * countLabel;
@property (nonatomic,strong) AVAudioPlayer * player;
@property (nonatomic,strong) AVAudioPlayer * player2;

@end

@implementation BSKTimeKeepingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"stopwatch_tick" ofType:@"wav"];
    NSURL * fileURL = [NSURL fileURLWithPath:filePath];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL fileTypeHint:@"wav" error:NULL];
    self.player.numberOfLoops = -1;
    [self.player prepareToPlay];
    NSString * filePath2 = [[NSBundle mainBundle] pathForResource:@"records" ofType:@"wav"];
    NSURL * fileURL2 = [NSURL fileURLWithPath:filePath2];
    self.player2 = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL2 fileTypeHint:@"wav" error:NULL];
    [self.player2 prepareToPlay];
    
}

-(void)initializeUserInterface{
    self.view.backgroundColor = [UIColor clearColor];
    
    
    self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.startButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_start_normal"] forState:UIControlStateNormal];
    [self.startButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_stop_normal"] forState:UIControlStateSelected];
    [self.view addSubview:self.startButton];
    
    self.resetButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.resetButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_reset_normal"] forState:UIControlStateNormal];
    [self.resetButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_meter_times_normal"] forState:UIControlStateSelected];
    self.resetButton.userInteractionEnabled = NO;
    self.resetButton.alpha = 0.2;
    [self.resetButton addTarget:self action:@selector(resetButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.resetButton];
    
    
    self.noteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.noteButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_record_plate"] forState:UIControlStateNormal];
    [self.noteButton setBackgroundImage:[UIImage imageNamed:@"stopwatch_btn_record_list"] forState:UIControlStateSelected];
    [self.view addSubview:self.noteButton];
    [self.noteButton addTarget:self action:@selector(noteAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.resetButton.sd_layout
    .centerXIs(self.view.width/2)
    .widthIs(self.view.width/3-10)
    .heightEqualToWidth()
    .bottomSpaceToView(self.view,40);
    
    self.startButton.sd_layout
    .centerYEqualToView(self.resetButton)
    .rightSpaceToView(self.resetButton,10)
    .widthRatioToView(self.resetButton,1)
    .heightEqualToWidth();
    
    self.noteButton.sd_layout
    .centerYEqualToView(self.resetButton)
    .leftSpaceToView(self.resetButton,10)
    .widthRatioToView(self.resetButton,1)
    .heightEqualToWidth();
    
    self.resetLabel = [[UILabel alloc]init];
    self.resetLabel.text = @"重置";
    self.resetLabel.alpha = 0.2;
    self.resetLabel.font = [UIFont systemFontOfSize:15];
    self.resetLabel.textAlignment = NSTextAlignmentCenter;
    self.resetLabel.textColor = [UIColor whiteColor];
    [self.view addSubview: self.resetLabel];
    
    self.resetLabel.sd_layout
    .leftEqualToView(self.resetButton)
    .rightEqualToView(self.resetButton)
    .heightIs(30)
    .topSpaceToView(self.resetButton,0);
    
    
    self.noteLabel = [[UILabel alloc]init];
    self.noteLabel.text = @"记录";
    self.noteLabel.font = [UIFont systemFontOfSize:15];
    self.noteLabel.textAlignment = NSTextAlignmentCenter;
    self.noteLabel.textColor = [UIColor whiteColor];
    [self.view addSubview: self.noteLabel];
    
    self.noteLabel.sd_layout
    .leftEqualToView(self.noteButton)
    .rightEqualToView(self.noteButton)
    .heightIs(30)
    .topSpaceToView(self.noteButton,0);
    
    self.startLabel = [[UILabel alloc]init];
    self.startLabel.text = @"开始";
    self.startLabel.font = [UIFont systemFontOfSize:15];
    self.startLabel.textAlignment = NSTextAlignmentCenter;
    self.startLabel.textColor = [UIColor whiteColor];
    [self.startButton addTarget:self action:@selector(startTimer:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: self.startLabel];
    
    self.startLabel.sd_layout
    .leftEqualToView(self.startButton)
    .rightEqualToView(self.startButton)
    .heightIs(30)
    .topSpaceToView(self.startButton,0);
    
    
    
    self.contentView = [[UIView alloc]init];
    self.contentView.backgroundColor = [UIColor clearColor];
    self.contentView.layer.masksToBounds =YES;
    [self.view addSubview:self.contentView];
    
    self.contentView.sd_layout
    .leftSpaceToView(self.view,0)
    .widthIs(self.view.width)
    .topSpaceToView(self.view,0)
    .bottomSpaceToView(self.startButton,5);
    
    self.circleView = [[UIView alloc]init];
    [self.contentView addSubview:self.circleView];
    self.circleView.layer.cornerRadius= self.contentView.width*0.7/2;
    self.circleView.layer.borderWidth = 1;
    self.circleView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.circleView.backgroundColor = [UIColor clearColor];
    self.circleView.sd_layout
    .centerXIs(self.contentView.width/2)
    .widthIs(self.contentView.width*0.7)
    .heightEqualToWidth()
    .centerYIs(20+self.contentView.width*0.7/2);
    
    self.pointView = [[UIView alloc]init];
    [self.circleView addSubview:self.pointView];
    self.pointView.frame = CGRectMake(0, 0, self.contentView.width*0.7, self.contentView.width*0.7);
    self.pointView.backgroundColor = [UIColor clearColor];
    
    CALayer * redPointLayer = [CALayer layer];
    redPointLayer.bounds = CGRectMake(0, 0, 20, 20);
    redPointLayer.position = CGPointMake(self.pointView.bounds.size.width/2, 15);
    redPointLayer.backgroundColor = [UIColor redColor].CGColor;
    redPointLayer.cornerRadius = 10;
    [self.pointView.layer addSublayer:redPointLayer];
    
    self.countLabel = [[UILabel alloc]init];
    self.countLabel.text = @"点击【开始】开启秒表";
    self.countLabel.textColor = [UIColor whiteColor];
    self.countLabel.font = [UIFont systemFontOfSize:20];
    self.countLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:self.countLabel];
    self.countLabel.sd_layout
    .topSpaceToView(self.circleView,10)
    .leftSpaceToView(self.contentView,0)
    .rightSpaceToView(self.contentView,0)
    .heightIs(80);
    
    self.timeLabel = [[UILabel alloc]init];
    self.timeLabel.text = @"00:00.00";
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.font = [UIFont systemFontOfSize:40];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:self.timeLabel];
    
    self.timeLabel.sd_layout
    .centerYEqualToView(self.circleView)
    .centerXEqualToView(self.circleView)
    .widthRatioToView(self.contentView,1)
    .heightIs(30);
    
    self.subTimeLabel = [[UILabel alloc]init];
    self.subTimeLabel.text = @"00:00.00";
    self.subTimeLabel.textColor = [UIColor whiteColor];
    self.subTimeLabel.font = [UIFont systemFontOfSize:20];
    self.subTimeLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:self.subTimeLabel];
    self.subTimeLabel.sd_layout
    .centerXEqualToView(self.circleView)
    .topSpaceToView(self.timeLabel,10)
    .widthRatioToView(self.contentView,1)
    .heightIs(20);
    
    for (UIView* subview in self.view.subviews) {
        [subview updateLayout];
    }
    
    self.timetabel = [[UITableView alloc]init];
    self.timetabel.delegate = self;
    self.timetabel.dataSource = self;
    [self.timetabel registerClass:BSKTimeKeepingItemTableViewCell.self forCellReuseIdentifier:@"cell"];
    [self.contentView addSubview:self.timetabel];
    self.timetabel.backgroundColor = [UIColor clearColor];
//    self.timetabel.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.timetabel.sd_layout
    .leftSpaceToView(self.contentView,0)
    .rightSpaceToView(self.contentView,0)
    .topSpaceToView(self.contentView,self.contentView.height)
    .bottomSpaceToView(self.contentView,0);
    self.timetabel.alpha = 0;
    self.timetabel.rowHeight = 100;
    for (UIView* subview in self.view.subviews) {
        [subview updateLayout];
    }
   }

#pragma mark ButtonAction

-(void)noteAction:(UIButton *)sender{

    sender.selected = !sender.selected;
    if (sender.selected) {
        [UIView animateWithDuration:0.3 animations:^{
            self.countLabel.alpha = 0;
            self.circleView.alpha = 0;
            self.circleView.sd_layout
            .centerYIs(15);
            [self.circleView updateLayout];
        } completion:^(BOOL finished) {
            NSLog(@"%lf",self.contentView.height);
        }];
        
        [UIView animateWithDuration:0.3 delay:0.10 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            self.timetabel.alpha = 1;
            self.timetabel.sd_layout
            .topSpaceToView(self.contentView,65);
            [self.timetabel updateLayout];
            
        } completion:^(BOOL finished) {
            
        }];
    }else{
        CGPoint p = self.circleView.center;
        p.y = 20+self.view.width*0.7/2;
        [UIView animateWithDuration:0.3 animations:^{
            self.timetabel.alpha = 0;
            self.timetabel.sd_layout
            .topSpaceToView(self.contentView,self.contentView.height);
            [self.timetabel updateLayout];
        } completion:^(BOOL finished) {
            NSLog(@"%lf",self.contentView.height);
        }];
        
        [UIView animateWithDuration:0.3 delay:0.10 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.countLabel.alpha = 1;
            self.circleView.alpha = 1;
            self.circleView.sd_layout
            .centerYIs(20+self.contentView.width*0.7/2);
            [self.circleView updateLayout];
        } completion:^(BOOL finished) {
            
        }];
    }
 
}

-(void)resetButtonAction:(UIButton *)sender{
    if (sender.selected) {//计次
        [self.player2 setCurrentTime:0];
        [self.player2 play];
        NSDictionary *dic=@{@"minutes":@(self.minutes),@"secondes":@(self.second),@"mSecond":@(self.mSecond),
                            @"subMinutes":@(self.subMinutes),@"subSecondes":@(self.subSecond),@"subMSecond":@(self.subMSecond)};
        
        self.subMSecond = 0;
        self.subSecond = 0;
        self.subMinutes = 0;
        
        
        if (fabs(self.timetabel.contentOffset.y)<self.timetabel.rowHeight) {
            [self.timetabel setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        [self.timeDataSourceArray insertObject:dic atIndex:0];
        [self.timetabel insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        self.countLabel.text = [NSString stringWithFormat:@"共 %ld 条记录",self.timeDataSourceArray.count];
        UILabel * label = [[UILabel alloc]init];
        label.font = self.timeLabel.font;
        label.text = [NSString stringWithFormat:@"%.2ld:%.2ld.%.2ld",[dic[@"minutes"] integerValue],[dic[@"secondes"] integerValue],[dic[@"mSecond"] integerValue]];
        [label sizeToFit];
        label.center = self.timeLabel.center;
        label.textColor = self.timeLabel.textColor;
        [self.contentView addSubview:label];
        
        UILabel * plusOneLabel = [[UILabel alloc]init];
        plusOneLabel.frame = self.resetButton.frame;
        plusOneLabel.textAlignment = NSTextAlignmentCenter;
        plusOneLabel.text = @"+1";
        plusOneLabel.textColor = [UIColor whiteColor];
        plusOneLabel.font = [UIFont systemFontOfSize:50];
        [self.view addSubview:plusOneLabel];
        CGPoint p = _resetButton.center;
        p.y-=100;
        [UIView animateWithDuration:0.5 animations:^{
            plusOneLabel.center =p;
            plusOneLabel.alpha = 0;
        } completion:^(BOOL finished) {
            [plusOneLabel removeFromSuperview ];
        }];
        if (!self.noteButton.selected) {
            CGPoint LabelCenter = label.center;
            LabelCenter.y-=100;
            [UIView animateWithDuration:0.5 animations:^{
                label.center = LabelCenter;
                label.alpha = 0;
            } completion:^(BOOL finished) {
                [label removeFromSuperview];
            }];
        }else{
            
            BSKTimeKeepingItemTableViewCell *cell = [self.timetabel cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            cell.timeLabel.alpha = 0;
            cell.numberLabe.alpha = 0;
            cell.intervalLabel.alpha = 0;
            CGRect rect = [self.contentView convertRect:cell.timeLabel.frame fromView:cell];
//            rect = [self.view convertRect:rect toView:self.contentView];
            NSLog(@"%lf,%lf,%lf,%lf",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
            [UIView animateWithDuration:0.25 animations:^{
                label.transform = CGAffineTransformMakeScale(cell.timeLabel.font.pointSize/label.font.pointSize, cell.timeLabel.font.pointSize/label.font.pointSize) ;
                label.frame = rect;
            } completion:^(BOOL finished) {
                cell.timeLabel.alpha = 1;
                [label removeFromSuperview];
            }];
            [UIView animateWithDuration:0.6 animations:^{
                cell.numberLabe.alpha = 1;
                cell.intervalLabel.alpha = 1;
            }];
        }
    }
    else{//重置
        [UIView animateWithDuration:0.25 animations:^{
            self.pointView.layer.affineTransform = CGAffineTransformMakeRotation(0);
        }];
        
        self.countLabel.text = @"点击【开始】开启秒表";
        self.startLabel.text = @"开始";
        self.resetButton.alpha = 0.2;
        self.resetLabel.alpha = 0.2;
        self.resetButton.userInteractionEnabled = NO;
        self.mSecond = 0;
        self.second = 0;
        self.minutes = 0;
        self.subMSecond = 0;
        self.subSecond = 0;
        self.subMinutes = 0;
        self.timeLabel.text = @"00:00.00";
        self.subTimeLabel.text = @"00:00.00";
        [self.timeDataSourceArray removeAllObjects];
        [self.timetabel reloadData];
    }
}

-(void)startTimer:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.player play];
        self.startLabel.text = @"暂停";
        self.resetLabel.text = @"计次";
        self.resetButton.selected = YES;
        self.resetButton.alpha = 1;
        self.resetButton.userInteractionEnabled = YES;
        self.resetLabel.alpha = 1;
        
        /// 初始化一个gcd队列.
        
        dispatch_queue_t timerQueue = dispatch_queue_create("timerQueue", 0);
        
        /// 创建 gcd timer.
        
        _timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerQueue);
        
        double interval = 0.01 * NSEC_PER_SEC; /// 间隔
        
        dispatch_source_set_timer(_timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
        /// 定时器block设置
        dispatch_source_set_event_handler(_timerSource, ^{
            self.mSecond +=1;
            self.subMSecond+=1;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.timeLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld.%.2ld",self.minutes,self.second,self.mSecond];
                self.subTimeLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld.%.2ld",self.subMinutes,self.subSecond,self.subMSecond];
                double x = self.mSecond/100.0;
                double a = (0.5-x)/fabs(0.5-x);
                double y =a*(2*pow(x,2))+((1-a)/2)*(4*x-1);
                self.pointView.layer.affineTransform = CGAffineTransformMakeRotation(y*2*M_PI);
            });
        });
        /// 唤起定时器任务.
        dispatch_resume(_timerSource);
    }
    else{
        [self.player stop];
        dispatch_source_cancel(_timerSource);
        self.startLabel.text = @"继续";
        self.resetLabel.text = @"重置";
        self.resetButton.selected = NO;
    }
    self.countLabel.text = [NSString stringWithFormat:@"共 %ld 条记录",self.timeDataSourceArray.count];
}


#pragma mark UITableViewDelegate,UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.timeDataSourceArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BSKTimeKeepingItemTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSDictionary * dic = self.timeDataSourceArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.timeLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld.%.2ld",[dic[@"minutes"] integerValue],[dic[@"secondes"] integerValue],[dic[@"mSecond"] integerValue]];
    cell.numberLabe.text = [NSString stringWithFormat: @"计次：%ld次",self.timeDataSourceArray.count-indexPath.row];
    cell.intervalLabel.text = [NSString stringWithFormat:@"间隔 %.2ld:%.2ld.%.2ld",[dic[@"subMinutes"] integerValue],[dic[@"subSecondes"] integerValue],[dic[@"subMSecond"] integerValue]];
    return cell;
}

#pragma mark setter

-(void)setMSecond:(NSInteger)mSecond{
    if (mSecond>=100) {
        mSecond=0;
        self.second+=1;
    }
    _mSecond=mSecond;
}

-(void)setSecond:(NSInteger)second{
    if (second>=60) {
        second = 0;
        self.minutes+=1;
    }
    _second = second;
}


-(void)setSubMSecond:(NSInteger)mSecond{
    if (mSecond>=100) {
        mSecond=0;
        self.subSecond+=1;
    }
    _subMSecond=mSecond;
}

-(void)setSubSecond:(NSInteger)second{
    if (second>=60) {
        second = 0;
        self.subMinutes+=1;
    }
    _subSecond = second;
}


#pragma mark getter

-(NSMutableArray *)timeDataSourceArray{
    if (_timeDataSourceArray) {
        return _timeDataSourceArray;
    }
    
    _timeDataSourceArray = [NSMutableArray array];
    return _timeDataSourceArray;
}

@end
